package ms.shop.controller;

import ms.common.exception.BizException;
import ms.common.util.file.FileClient;
import ms.shop.config.Constant;
import ms.shop.config.ResponseCode;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Project Name: ms
 * File Name: FileController
 * Package Name: ms.shop.controller
 * Date: 2018/5/31  9:39
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public String upload(HttpServletRequest req) throws IOException {
        String url = "";
        //创建一个通用的多部分解析器
        MultipartFile imgFile;
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
        if(multipartResolver.isMultipart(req)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
            imgFile = multiRequest.getFile("file");

            if(null == imgFile) {
                throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "图片不能为空");
            }
            String imgPrefix = imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf(".")+1);

            //七牛文件上传
            FileClient fileClient = new FileClient(Constant.accessKey, Constant.secretKey, Constant.bucket, Constant.url, Constant.zone);
            url = fileClient.uploadFile(imgFile.getInputStream(), imgPrefix, Constant.zone);
        }
        return url;

    }
}
